//go:build ignore
// +build ignore

// Build script for pwsh-go with custom icon embedding
// Usage: go run scripts/build-with-icon.go

package main

import (
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"

	"github.com/tc-hib/winres"
)

func main() {
	// 获取当前工作目录（应该是项目根目录）
	wd, err := os.Getwd()
	if err != nil {
		log.Fatalf("Failed to get working directory: %v", err)
	}
	
	iconPath := filepath.Join(wd, "assets", "icon.ico")
	buildDir := filepath.Join(wd, "cmd", "pwsh-go")
	resourceFile := filepath.Join(buildDir, "resource.syso")

	fmt.Println("Building pwsh-go with embedded icon...")

	// 1. 生成资源文件
	fmt.Println("Generating resource file...")
	rs := winres.ResourceSet{}

	// 打开图标文件
	f, err := os.Open(iconPath)
	if err != nil {
		log.Fatalf("Failed to open icon file: %v", err)
	}
	defer f.Close()

	// 添加图标到资源
	icon, err := winres.LoadICO(f)
	if err != nil {
		log.Fatalf("Failed to load icon from ICO: %v", err)
	}
	rs.SetIcon(winres.Name("ICON"), icon)

	// 写入资源文件
	fout, err := os.Create(resourceFile)
	if err != nil {
		log.Fatalf("Failed to create resource file: %v", err)
	}
	defer fout.Close()

	err = rs.WriteObject(fout, winres.ArchAMD64)
	if err != nil {
		log.Fatalf("Failed to write resource object: %v", err)
	}

	fmt.Println("Resource file generated successfully.")

	// 2. 构建可执行文件
	fmt.Println("Building executable...")
	cmd := exec.Command("go", "build", "-o", "pwsh-go.exe")
	cmd.Dir = buildDir
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	err = cmd.Run()
	if err != nil {
		log.Fatalf("Failed to build executable: %v", err)
	}

	fmt.Println("Build completed successfully!")
	fmt.Println("pwsh-go.exe has been built with embedded icon.")
	fmt.Println("\nNote: If the icon doesn't appear immediately in Windows Explorer:")
	fmt.Println("1. Try refreshing the folder (F5)")
	fmt.Println("2. Clear icon cache: ie4uinit.exe -show")
	fmt.Println("3. Restart Windows Explorer if necessary")
}